package com.kaizeli.website.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 预警WebSocket处理器
 * 负责管理WebSocket连接和消息推送
 */
@Slf4j
@Component
public class WarningWebSocketHandler extends TextWebSocketHandler {

    /**
     * 存储所有活跃的WebSocket会话
     * Key: sessionId, Value: WebSocketSession
     */
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    /**
     * 客户端连接成功后调用
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String sessionId = session.getId();
        sessions.put(sessionId, session);
        log.info("WebSocket连接建立 - SessionId: {}, 当前在线用户数: {}", sessionId, sessions.size());
        
        // 发送欢迎消息
        String welcomeMsg = String.format("{\"type\":\"connect\",\"message\":\"预警推送服务已连接\",\"sessionId\":\"%s\"}", sessionId);
        session.sendMessage(new TextMessage(welcomeMsg));
    }

    /**
     * 接收客户端消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("收到客户端消息 - SessionId: {}, Message: {}", session.getId(), payload);
        
        // 可以根据客户端消息类型做不同处理
        // 例如：心跳检测、订阅特定类型的预警等
    }

    /**
     * 连接关闭后调用
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String sessionId = session.getId();
        sessions.remove(sessionId);
        log.info("WebSocket连接关闭 - SessionId: {}, 状态: {}, 当前在线用户数: {}", 
                sessionId, status, sessions.size());
    }

    /**
     * 连接出错时调用
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String sessionId = session.getId();
        log.error("WebSocket传输错误 - SessionId: {}, 错误: {}", sessionId, exception.getMessage());
        
        if (session.isOpen()) {
            session.close();
        }
        sessions.remove(sessionId);
    }

    /**
     * 向所有连接的客户端广播消息
     * @param message 要广播的消息（JSON格式）
     */
    public void broadcastWarning(String message) {
        log.info("广播预警消息给 {} 个客户端: {}", sessions.size(), message);
        
        sessions.forEach((sessionId, session) -> {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                    log.debug("预警消息已发送到 SessionId: {}", sessionId);
                } catch (IOException e) {
                    log.error("发送预警消息失败 - SessionId: {}, 错误: {}", sessionId, e.getMessage());
                }
            } else {
                // 移除已关闭的连接
                sessions.remove(sessionId);
                log.warn("移除已关闭的会话 - SessionId: {}", sessionId);
            }
        });
    }

    /**
     * 向指定客户端发送消息
     * @param sessionId 会话ID
     * @param message 要发送的消息（JSON格式）
     */
    public void sendMessageToSession(String sessionId, String message) {
        WebSocketSession session = sessions.get(sessionId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
                log.info("预警消息已发送到指定客户端 - SessionId: {}", sessionId);
            } catch (IOException e) {
                log.error("发送预警消息失败 - SessionId: {}, 错误: {}", sessionId, e.getMessage());
            }
        } else {
            log.warn("会话不存在或已关闭 - SessionId: {}", sessionId);
        }
    }

    /**
     * 获取当前在线客户端数量
     */
    public int getOnlineCount() {
        return sessions.size();
    }
}

